import React from 'react';
import {Table, Input, InputNumber, Popconfirm, Form, Card, Select, message, Tooltip, Button, DatePicker} from 'antd';
import SearchForm from '../../components/AutoForm/SearchForm';
import {connect} from "dva";
import moment from "moment";
import EditForm from "../../components/AutoForm/EditForm";
const { TextArea } = Input;

@connect(({expense, user, loading}) => ({
  tableLoading: loading.effects['expense/page'],
  rejectLoading: loading.effects['expense/reject'],
  tableData: expense.pageList,
  pagination: expense.pagination,
  columns: expense.columns,
  searchFields: expense.searchFields,
  searchValues: expense.searchValuesPa,
  editId: expense.editId,
  selectionIds: expense.selectionIds,
  currentUser: user.currentUser
}))
class EditableTable extends React.Component {

  state = {
    rejectModal: false,
    rejectForm: {},
    rejectRows: [
      {
        cols: [
          {
            label: '驳回理由',
            name: 'rejectCase',
            md: 12,
            rules: [{ required: true, message: ' ' }],
            component: <TextArea rows={4} placeholder="请输入驳回理由" />,
          },
        ],
      },
    ],
  };

  rowClassName = (record, index) => {
    if (record.status === 'LEADER_PASS') {
      return 'orderParent';
    }
  };

  componentDidMount() {
    this.handleSearch();
  }

  handleRejectChange = fields => {
    this.setState({
      rejectForm: fields,
    });
  };

  handleRejectVisible = () => {
    this.setState({
      rejectModal: false,
    });
  };

  handleRejectSub = fields => {
    const { dispatch, selectionIds } = this.props;
    if (selectionIds.length !== 1) {
      return message.error('请选择一条要驳回的报销！');
    }

    dispatch({
      type: 'expense/reject',
      payload: {
        id: selectionIds[0],
        ...fields,
        status: 'ENTRY'
      },
    }).then(() => {
      this.handleSearch();
      this.setState({ rejectModal: false });
    });
  };

  handleSearchChange = (fields) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'expense/handleSearchChangePa',
      payload: fields
    })
  }

  handleSearch = (flag) => {
    const {dispatch, pagination, searchValues} = this.props;
    let pageParam = {pageSize: pagination.pageSize, current: flag==='btn' ? 1 : pagination.current}
    let searchParam = {};
    Object.keys(searchValues).map((key) => {
      if (key === 'createTimeArray') {
        const dateArray = searchValues[key]['value'];
        if (dateArray && dateArray.length) {
          let startTime = moment(dateArray[0]);
          let endTime = moment(dateArray[1]);
          searchParam['expTimeStr'] = startTime.format('YYYY-MM-DD HH:mm:ss');
          searchParam['expTimeEnd']= endTime.format('YYYY-MM-DD HH:mm:ss');
        }
      }else{
        searchParam[key] = searchValues[key]['value'];
      }
    })
    const param = {
      ...searchParam,
      ...pageParam,
      flag: 'LEADER_PASS'
    };
    dispatch({
      type: 'expense/page',
      payload: param
    })
  }

  onChange = (selectedRowKeys, selectedRows) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'expense/handleSelection',
      payload: selectedRowKeys
    })
  }

  handleSend = () => {
    const { dispatch, selectionIds } = this.props;
    if (!selectionIds.length) {
      return message.error('请选择一行要提交的数据');
    }
    dispatch({
      type: 'expense/send',
      payload: {ids: selectionIds, status: 'PAY_ALLOW'}
    }).then(() => {
      this.handleSearch();
    });
  }

  handleReject = () => {
    const { selectionIds } = this.props;
    if (selectionIds.length !== 1) {
      return message.error('请选择一条记录！');
    }
    this.setState({ rejectModal: true });

  }
  render() {
    const {
      columns,
      pagination,
      tableLoading,
      tableData,
      searchFields,
      searchValues,
      dispatch,
      rejectLoading
    } = this.props;

    const { rejectModal, rejectForm, rejectRows } = this.state;

    pagination.onChange = (page, pageSize) => {
      let searchParam = {};
      Object.keys(searchValues).map((key) => {
        searchParam[key] = searchValues[key]['value'];
      })
      dispatch({
        type: 'expense/page',
        payload: {
          ...searchParam,
          current: page,
          pageSize
        }
      })
    }
    pagination.onShowSizeChange = (current, size) => {
      let searchParam = {};
      Object.keys(searchValues).map((key) => {
        searchParam[key] = searchValues[key]['value'];
      })
      dispatch({
        type: 'expense/page',
        payload: {
          ...searchParam,
          current: current,
          pageSize: size
        }
      })
    }

    const rowSelection = {
      type: "checkbox",
      selections: this.props.selectedRows,
      selectedRowKeys: this.props.selectionIds,
      onChange: this.onChange,
      getCheckboxProps: record => ({
        disabled: record.status !== 'LEADER_PASS', // Column configuration not to be checked
      }),
    };

    return (
      <Card bodyStyle={{padding: 0}}>
        <SearchForm
          header="报销->操作"
          layout="inline"
          onFieldsChange={this.handleSearchChange}
          isSend={true}
          isReject={true}
          onSend={this.handleSend}
          onSubmit={() => {this.handleSearch('btn')}}
          onReject={this.handleReject}
          fields={searchFields}
          fieldValue={searchValues}
        />
        <Table
          bordered
          rowKey="id"
          loading={tableLoading}
          dataSource={tableData}
          columns={columns}
          rowSelection={rowSelection}
          rowClassName={this.rowClassName}
          scroll={{x: 'max-content'}}
          size="small"
          pagination={pagination}
        />

        <EditForm
          title="驳回"
          rows={rejectRows}
          fieldValue={rejectForm}
          onFieldsChange={this.handleRejectChange}
          onCancel={this.handleRejectVisible}
          onOk={this.handleRejectSub}
          confirmLoading={rejectLoading}
          visible={rejectModal}
        />
      </Card>
    );
  }
}

const EditableFormTable = Form.create()(EditableTable);
export default EditableFormTable;
